<template>
    <div class="stats-container">
        <div class="chart-wrapper" v-if="props.flatChartData.categories.length > 0">
            <div ref="flatChartRef" class="chart"></div>
        </div>
        <div class="chart-wrapper" v-if="props.nestedChartData.categories.length > 0">
            <div ref="nestedChartRef" class="chart"></div>
        </div>
        <div class="chart-wrapper" v-if="props.verticalChartData?.categories?.length">
            <div ref="verticalChartRef" class="chart"></div>
        </div>
    </div>
    <p
        class="placeholder"
        v-if="props.flatChartData.categories.length === 0 && props.nestedChartData.categories.length === 0"
    >
        Please enter the search conditions, the chart will be displayed here
    </p>
</template>

<script setup lang="ts" name="StatsChart">
    import { ref, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue';
    import debounce from 'lodash/debounce';
    import * as echarts from 'echarts';
    import { colorList, cancerDict } from '@/common/util';

    const props = defineProps({
        flatChartData: {
            type: Object,
            default: null
        },
        nestedChartData: {
            type: Object,
            default: null
        },
        verticalChartData: {
            type: Object,
            default: null
        }
    });

    const hasAnyData = computed(
        () =>
            props.flatChartData.categories?.length ||
            props.nestedChartData.categories?.length ||
            props.verticalChartData?.categories?.length
    );

    const logValues = props.flatChartData.values.map((v: number) => {
        // 避免 log(0) 或负数，通常处理方式是加个偏移
        return v > 0 ? Math.log10(v) : 0;
    });

    const flatChartRef = ref(null);
    const nestedChartRef = ref(null);
    const verticalChartRef = ref(null);
    let flatChart: any, nestedChart: any, verticalChart: any;

    async function renderCharts() {
        if (props.flatChartData.categories.length == 0 && props.nestedChartData.categories.length == 0) return;
        if (props.flatChartData.categories.length > 0) {
            await nextTick();
            if (!flatChart) flatChart = echarts.init(flatChartRef.value);
            flatChart.setOption({
                tooltip: {
                    formatter: (params: any) => {
                        console.log(params);
                        // params.data.realValue 就是原始数值
                        return `${params.name}: ${params.data.realValue}`;
                    }
                },
                grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
                xAxis: {
                    type: 'value',
                    name: 'Max Copy Number of different Cell line',
                    nameLocation: 'center',
                    nameGap: 25,
                    nameTextStyle: {
                        fontSize: 20
                    },
                    axisLabel: {
                        formatter: (val:any) => {
                            // 使用富文本
                            if (Number.isInteger(val) && val > 0) {
                                return `{base|10}{exp|${val}}`;
                            } else if (val === 0) {
                                return 1;
                            }
                        },
                        rich: {
                            base: {
                                // 底数的样式
                                fontSize: 12 // 可以根据需要调整字体大小
                            },
                            exp: {
                                // 指数的样式
                                fontSize: 8, // 通常指数会比底数小
                                verticalAlign: 'top', // 关键：将文本基线向上对齐，实现上标效果
                                padding: [0, 0, 0, 0] // 适当调整内边距，使其更靠近底数
                            }
                        }
                    },
                    axisLine: { show: true, lineStyle: { color: '#000', width: 1 } },
                    axisTick: { lineStyle: { color: '#000' } }
                },
                yAxis: {
                    type: 'category',
                    name: 'Cell Line',
                    nameLocation: 'start',
                    nameTextStyle: {
                        fontSize: 15
                    },
                    inverse: true, // 反转排序
                    data: props.flatChartData.categories,
                    axisLine: { show: true, lineStyle: { color: '#000', width: 1 } },
                    axisTick: { lineStyle: { color: '#000' } }
                },
                series: [
                    {
                        type: 'bar',
                        data: props.flatChartData.values.map((v: number) => {
                            return {
                                value: v > 0 ? Math.log10(v) : 0, // 柱子高度用 log10
                                realValue: v // 保留原始值，用于 tooltip
                            };
                        }),
                        itemStyle: {
                            color: (params: any) => colorList[params.dataIndex % colorList.length]
                        },
                        barMaxWidth: 10,
                        barMinWidth: 5
                    }
                ]
            });
        }

        // if (props.nestedChartData.categories.length > 0) {
        //     await nextTick();
        //     if (!nestedChart) nestedChart = echarts.init(nestedChartRef.value);

        //     const flatNames = props.flatChartData.categories;
        //     const nestedNames = props.nestedChartData.series.map((s: any) => s.name);
        //     const allNames = Array.from(new Set([...flatNames, ...nestedNames]));

        //     // 2. 生成 name→color 的映射
        //     const colorMap: any = {};
        //     allNames.forEach((name, idx) => {
        //         colorMap[name] = colorList[idx % colorList.length];
        //     });

        //     const totals = props.nestedChartData.counts_by_category || {};

        //     nestedChart.setOption({
        //         tooltip: {
        //             trigger: 'item',
        //             formatter: ({ seriesName, value }: any) => {
        //                 return `${seriesName}: ${value}%`;
        //             }
        //         },
        //         grid: { left: '0', right: '8%', bottom: '8%', containLabel: true },

        //         // legend: { data: props.nestedChartData.series.map(s => s.name) },
        //         xAxis: {
        //             type: 'value',
        //             name: 'Proportion of Copy Number of different Cell line',
        //             nameLocation: 'center',
        //             nameGap: 25,
        //             nameTextStyle: {
        //                 fontSize: 20
        //             },
        //             axisLine: { show: true, lineStyle: { color: '#000', width: 1 } },
        //             axisTick: { lineStyle: { color: '#000' } }
        //         },
        //         yAxis: {
        //             type: 'category',
        //             name: 'Cell Line(Total)',
        //             nameTextStyle: {
        //                 fontSize: 15
        //             },
        //             data: props.nestedChartData.categories,
        //             axisLine: { show: true, lineStyle: { color: '#000', width: 1 } },
        //             axisLabel: {
        //                 interval: 0, // 强制每个都显示
        //                 color: '#000',
        //                 formatter: (value: string) => {
        //                     return `${value} (${totals[value]})`
        //                 },
        //                 labelLayout: {
        //                     hideOverlap: false // 尝试设置为 false
        //                 }
        //             },
        //         },
        //         series: props.nestedChartData.series.map((s: any) => ({
        //             ...s,
        //             type: 'bar',
        //             stack: 'oncotree',
        //             barMaxWidth: 10,
        //             barMinWidth: 10,
        //             itemStyle: {
        //                 color: colorMap[s.name]
        //             }
        //         }))
        //     });
        // }
        if (props.nestedChartData.categories.length > 0) {
            await nextTick();
            if (!nestedChart) nestedChart = echarts.init(nestedChartRef.value);

            // const flatNames = props.flatChartData.categories || [];
            // const nestedNames = (props.nestedChartData.series || []).map((s: any) => s.name);
            // const allNames = Array.from(new Set([...flatNames, ...nestedNames]));

            // // 生成 name→color 的映射
            // const colorMap: any = {};
            // allNames.forEach((name, idx) => {
            //     colorMap[name] = colorList[idx % colorList.length];
            // });

            // counts_by_category: { "Breast": 4, ... }
            // const counts: Record<string, number> = props.nestedChartData.counts_by_category || {};


            // 构造 series（后端已经返回每个 series 的整数 data）
            // const seriesList = (props.nestedChartData.series || []).map((s: any) => ({
            //     ...s,
            //     type: 'bar',
            //     stack: 'oncotree',
            //     barMaxWidth: 10,
            //     barMinWidth: 5,
            //     itemStyle: {
            //         color: colorMap[s.name]
            //     },
            //     // 不显示每段的 label，避免太拥挤
            //     label: { show: false }
            // }));
            const categories = props.nestedChartData.categories || [];
            const cateDict = props.nestedChartData.counts_by_category || {}
            let countsMap: Record<string, number> = props.nestedChartData.counts_by_category || {};

            // 如果没有 counts_by_category，尝试从后端可能返回的单一 series 中推断
            if ((!countsMap || Object.keys(countsMap).length === 0) && Array.isArray(props.nestedChartData.series) && props.nestedChartData.series.length === 1) {
                const backendData = props.nestedChartData.series[0].data || [];
                // backendData 的长度应与 categories 对应
                countsMap = {};
                categories.forEach((cat: string, i: number) => {
                    const v = backendData[i];
                    countsMap[cat] = typeof v === 'number' ? v : (v && v.value ? v.value : 0);
                });
            }

            const colorMap: Record<string, string> = {};
            categories.forEach((name: string, idx: number) => {
                colorMap[name] = colorList[idx % colorList.length];
            });

            const counts = categories.map((cat: string) => countsMap[cat]);

            const seriesData = categories.map((cat: string) => {
                const val = countsMap[cat] ?? 0;
                return {
                    value: val,
                    // 保留原始值字段（可选），tooltip 可直接取 params.value
                    real: val,
                    // 每根柱子单独颜色
                    itemStyle: { color: colorMap[cat] }
                };
            });

            // 计算横轴最大值（取 totals 的最大值，至少为 1）
            const totalsArray:any = Object.values(counts);
            const maxTotal = totalsArray.length ? Math.max(...totalsArray) : 1;

            nestedChart.setOption({
                tooltip: {
                    trigger: 'item',
                    // params: { componentType, seriesType, seriesIndex, seriesName, name, dataIndex, data, value }
                    formatter: (params: any) => {
                        // 当 trigger ='item' 时 params 为单个数据项对象
                        const category = params.name; // y 轴的类别
                        return `${category}: ${cateDict[category]}`;
                    }
                },
                grid: { left: '0', right: '8%', bottom: '8%', containLabel: true },

                xAxis: {
                    type: 'value',
                    name: 'Number of different Cell line',
                    nameLocation: 'center',
                    nameGap: 25,
                    nameTextStyle: {
                        fontSize: 20
                    },
                    // 设一个合理的上限，给视觉保留空间
                    min: 0,
                    // max: Math.max(maxTotal, 1),
                    axisLine: { show: true, lineStyle: { color: '#000', width: 1 } },
                    axisTick: { lineStyle: { color: '#000' } },
                    axisLabel: {
                        formatter: (v: any) => `${v}` // 保证显示整数
                    }
                },

                yAxis: {
                    type: 'category',
                    name: 'Cell Line (Total)',
                    nameTextStyle: { fontSize: 15 },
                    data: props.nestedChartData.categories,
                    axisLine: { show: true, lineStyle: { color: '#000', width: 1 } },
                    axisLabel: {
                        interval: 0,
                        color: '#000',
                        formatter: (value: string) => {
                            const tot = counts[value] ?? 0;
                            return `${value} (${cateDict[value]})`;
                        },
                        // 如果需要更紧凑显示，可调整下面两个属性
                        rich: {} // 占位，可按需增加富文本样式
                    },
                    labelLayout: { hideOverlap: true }
                },

                series: [
                    {
                        name: 'Counts',
                        type: 'bar',
                        data: seriesData,
                        // 不使用 stack（不堆叠）
                        barMaxWidth: 18,
                        barMinWidth: 8,
                    }
                ]
            });
        }

        if (props.verticalChartData?.categories?.length) {
            await nextTick();
            if (!verticalChart) verticalChart = echarts.init(verticalChartRef.value);
            verticalChart.setOption({
                title: {
                    text: `${props.verticalChartData.gene} CNV Distribution`,
                    left: 'center', // 可选：居中显示标题
                    textStyle: {
                        fontSize: 25,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    // params 是数组：每个堆叠部分对应一个元素
                    formatter: function (params: any) {
                        if (!Array.isArray(params) || params.length === 0) return '';

                        // 标题使用 category（横坐标）
                        const category = params[0].axisValueLabel ?? params[0].name ?? '';
                        const fullName = cancerDict[category] ? cancerDict[category] + ' (' + category + ')' : category;

                        // 计算总百分比和总人数
                        let totalPercent = 0;
                        let totalCount = 0;
                        for (let i = 0; i < params.length; i++) {
                            const val = Number(params[i].value) || 0;
                            const cnt = params[i].data && params[i].data.count !== undefined ? params[i].data.count : 0;
                            totalPercent += val;
                            totalCount += cnt;
                        }
                        // 开始构建 html 表格
                        let html = `<div style="font-weight:700;margin-bottom:6px;">${fullName}</div>`;
                        html += `<div style="margin-bottom:6px;color:#444;">CNV alterations occurred in ${totalPercent.toFixed(
                            2
                        )}% of ${totalCount} patients</div>`;
                        html += '<table style="border-collapse:collapse;font-size:12px;">';

                        // 表头（可选）
                        html += '<tr>';
                        html += '<th style="text-align:left;padding:2px 150px 2px 0;">Type</th>'; // marker + name
                        html += '<th style="text-align:left;padding:2px 12px;">Frequency</th>';
                        html += '</tr>';

                        // 按 params 顺序逐行加入（只显示 value > 0 的行）
                        for (let i = 0; i < params.length; i++) {
                            const p = params[i];
                            // p.value 是数值（百分比），p.data.count 是后端传回的绝对值
                            console.log(p)
                            const val = Number(p.value) || 0;
                            const cnt = p.data && p.data.count !== undefined ? p.data.count : '';
                            // if (val === 0) continue; // 可选：不显示为 0 的项
                            // marker 是 echarts 自动提供的彩色小圆点 html
                            const marker = p.marker ?? '';
                            const patientStr = (cnt === 1 || cnt === 0)  ? 'patient' : 'patients';
                            html += '<tr>';
                            html += `<td style="padding:2px 8px 2px 0;white-space:nowrap;">${marker}${p.seriesName}: </td>`;
                            if (cnt != 0) {
                                html += `<td style="text-align:left;padding:2px 12px;">${val.toFixed(
                                    2)}% (${cnt} ${patientStr})</td>`;
                            } else if (cnt === 0) {
                                html += `<td style="text-align:left;padding:2px 12px;">${val}% (${cnt} ${patientStr})</td>`;
                            }
                            html += '</tr>';
                        }

                        html += '</table>';
                        return html;
                    }
                },
                grid: { left: '10%', right: '10%', bottom: '15%', containLabel: true },
                xAxis: {
                    type: 'category',
                    name: 'Cancer type',
                    nameLocation: 'middle',
                    nameGap: 50,
                    nameTextStyle: {
                        fontSize: 20
                    },
                    data: props.verticalChartData.categories,
                    axisLabel: { rotate: 45, interval: 0, color: '#000' },
                    axisLine: { show: true, lineStyle: { color: '#000', width: 1 } }
                },
                yAxis: {
                    type: 'value',
                    max: 100,
                    name: 'Proportion(%)',
                    nameLocation: 'middle',
                    nameGap: 30,
                    nameTextStyle: {
                        fontSize: 20
                    },
                    axisLine: { show: true, lineStyle: { color: '#000', width: 1 } }
                },
                series: props.verticalChartData.series.map((s: any) => ({
                    ...s,
                    type: 'bar',
                    stack: 'total',
                    barMaxWidth: 10,
                    barMinWidth: 10
                }))
            });
        }
    }

    watch(() => [props.flatChartData, props.nestedChartData, props.verticalChartData], renderCharts, {
        immediate: true,
        deep: true
    });

    const onResize = debounce(() => {
        if (flatChart) flatChart.resize();
        if (nestedChart) nestedChart.resize();
        if (verticalChart) verticalChart.resize();
    }, 300);

    onMounted(() => {
        window.addEventListener('resize', onResize);
    });
    onBeforeUnmount(() => {
        window.removeEventListener('resize', onResize);
        onResize.cancel && onResize.cancel();
    });
</script>

<style scoped>
    .stats-container {
        display: flex;
        flex-wrap: wrap;
        gap: 24px;
    }
    .chart-wrapper {
        flex: 1 1 45%;
    }
    .chart {
        width: 100%;
        height: 400px;
    }
    .placeholder {
        color: #888;
        font-size: 16px;
        padding: 40px;
    }
</style>
